package com.qxzn.module.mine.activity;

import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.AppCompatEditText;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.MotionEvent;
import android.view.View;
import android.view.animation.AnimationUtils;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.alibaba.fastjson.JSONObject;
import com.qxzn.app.api.api.HttpRequest;
import com.qxzn.app.bean.BaseBean;
import com.qxzn.app.page.BaseActivity;
import com.qxzn.app.page.util.Util;
import com.qxzn.app.page.widget.ToastUtil;
import com.qxzn.app.util.ActivityStack;
import com.qxzn.app.util.CommonUtil;
import com.qxzn.app.util.SharePreferenceUtil;
import com.qxzn.module.mine.R;
import com.qxzn.module.mine.R2;

import butterknife.BindView;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class ModifyPasswordActivity extends BaseActivity implements TextWatcher, View.OnTouchListener {
    public static String PARAM_SECURITY = "security";
    public static String PARAM_FAMILY = "family";
    public static String PARAM_USER = "user";
    @BindView(R2.id.modify_password_content)
    AppCompatEditText editText;
    @BindView(R2.id.btn_next)
    Button btn_next;
    @BindView(R2.id.showPassword)
    ImageView showPassword;
    @BindView(R2.id.modify_password_prompt)
    TextView prompt;

    private String params;

    @Override
    protected int initLayout() {
        return R.layout.activity_modify_password;
    }

    @Override
    protected void initView() {
        findViewById(R.id.loading_animator_img).startAnimation(AnimationUtils.loadAnimation(this, R.anim.rotate_repeat));
        Util.setPasswordFilter(editText);
        editText.addTextChangedListener(this);
        btn_next.setOnClickListener(this);
        showPassword.setOnClickListener(this);
        editText.setOnTouchListener(this);
        params = getIntent().getStringExtra(VerificationCode.EXTRA_ACTIVITY_PARAMS);
        prompt.setText(getPrompt());
        editText.setHint(getHint());
        editText.setInputType(getInputType());
    }

    private int getInputType() {
        if (PARAM_USER.equals(params))
            return EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD;
        return EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD;
    }

    private String getHint() {
        if (PARAM_USER.equals(params))
            return "不少于8位，至少包含数字和字母";
        return "6位数字";
    }

    private String getPrompt() {
        if (PARAM_FAMILY.equals(params))
            return "请为您的机器人\n小Π机器人\n设置一个新家庭密码";
        return "请为您的账号 " + CommonUtil.getSecurityPhoneString(getIntent().getStringExtra(VerificationCode.EXTRA_PHONE)) + "\n设置一个新" + (PARAM_SECURITY.equals(params) ? "安全" : "") + "密码";
    }

    @Override
    public void onClick(View view) {
        super.onClick(view);
        if (CommonUtil.isFastClick()) return;
        int id = view.getId();
        if (id == R.id.showPassword) {
            int res = R.mipmap.icon_pwd_hint;
            if (PARAM_USER.equals(params)) {
                if (editText.getInputType() == (EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD)) {
                    editText.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                    res = R.mipmap.icon_pwd_show;
                } else {
                    editText.setInputType(EditorInfo.TYPE_CLASS_TEXT | EditorInfo.TYPE_TEXT_VARIATION_PASSWORD);
                }
            } else {
                if (editText.getInputType() == (EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD)) {
                    editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_NORMAL);
                    res = R.mipmap.icon_pwd_show;
                } else {
                    editText.setInputType(EditorInfo.TYPE_CLASS_NUMBER | EditorInfo.TYPE_NUMBER_VARIATION_PASSWORD);
                }
            }
            editText.setSelection(editText.length());
            showPassword.setImageResource(res);
        } else if (id == R.id.btn_next) {
            String password = editText.getText().toString().trim();
            if (PARAM_FAMILY.equals(params)) {
                requestModifyFamilyPassword(password);
            } else if (PARAM_SECURITY.equals(params)) {
                requestModifySecurityPassword(password);
            } else {
                if (!CommonUtil.isLettersAndNumbers(password)) {
                    ToastUtil.showTextToast(this, getString(R.string.invalid_password_string));
                    return;
                } else {
                    requestModifyPassword(password);
                }
            }
            btn_next.setVisibility(View.INVISIBLE);
        }
    }

    private void requestModifySecurityPassword(String password) {
        // todo 请求修改
//        ToastUtil.showTextToast(this, "请求修改安全码");
        JSONObject params = new JSONObject();
        params.put("username", SharePreferenceUtil.getUserName(this));
        params.put("desk_password", password);
        HttpRequest.getService().updateSecurityPwd(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                btn_next.setVisibility(View.VISIBLE);
                BaseBean baseBean = response.body();
                if (baseBean.getCode() == 200) {
                    done();
                } else {
                    ToastUtil.showTextToast(ModifyPasswordActivity.this, baseBean.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                error();
            }
        });
    }

    private void requestModifyFamilyPassword(String password) {
        // todo 请求修改
//        ToastUtil.showTextToast(this, "请求修改家庭密码");
        JSONObject params = new JSONObject();
        params.put("username", SharePreferenceUtil.getUserName(this));
        params.put("device_id", SharePreferenceUtil.getDeviceId(this));
        params.put("family_password", password);
        HttpRequest.getService().updateFamilyPwd(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                btn_next.setVisibility(View.VISIBLE);
                BaseBean baseBean = response.body();
                if (baseBean.getCode() == 200) {
                    done();
                } else {
                    ToastUtil.showTextToast(ModifyPasswordActivity.this, baseBean.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                error();
            }
        });
    }

    private void requestModifyPassword(String password) {
        // todo 请求修改
//        ToastUtil.showTextToast(this, "请求修改登录密码");
        JSONObject params = new JSONObject();
        params.put("username", SharePreferenceUtil.getUserName(this));
        params.put("type", 2);
        params.put("new_password", password);
        params.put("old_password", "");
        HttpRequest.getService().updatePwd(HttpRequest.getDefaultBody(params)).enqueue(new Callback<BaseBean>() {
            @Override
            public void onResponse(Call<BaseBean> call, Response<BaseBean> response) {
                btn_next.setVisibility(View.VISIBLE);
                BaseBean baseBean = response.body();
                if (baseBean.getCode() == 200) {
                    SharePreferenceUtil.setPwd(getApplicationContext(),"");
                    done();
                } else {
                    ToastUtil.showTextToast(ModifyPasswordActivity.this, baseBean.getMsg());
                }
            }

            @Override
            public void onFailure(Call<BaseBean> call, Throwable t) {
                error();
            }
        });

    }

    private void error() {
        btn_next.setVisibility(View.VISIBLE);
        ToastUtil.showTextToast(ModifyPasswordActivity.this, getString(R.string.network_error));
    }

    private void done(){
        ToastUtil.showTextToast(this, getString(R.string.modify_password_success));
        ActivityStack.finishAllWithoutActivity("com.qxzn.app.desktoprobot.MainActivity", "com.qxzn.module.mine.activity.UserInfoActivity");
    }

    @Override
    protected void iniTitleBar() {
        tv_title.setText(getIntent().getStringExtra(VerificationCode.EXTRA_TITLE));
    }

    @Override
    protected void initData(Bundle savedInstanceState) {

    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        if (PARAM_USER.equals(params))
            btn_next.setEnabled(s.length() >= 8);
        else {
            btn_next.setEnabled(s.length() == 6);
            if (s.length() > 6) {
                if (PARAM_FAMILY.equals(params))
                    ToastUtil.showTextToast(this, getString(R.string.invalid_family_password_string));
                else
                    ToastUtil.showTextToast(this, getString(R.string.invalid_security_password_string));
            }
        }
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        // et.getCompoundDrawables()得到一个长度为4的数组，分别表示左右上下四张图片
        Drawable drawable = editText.getCompoundDrawables()[2];
        //如果右边没有图片，不再处理
        if (drawable == null)
            return false;
        //如果不是按下事件，不再处理
        if (event.getAction() != MotionEvent.ACTION_UP)
            return false;
        if (event.getX() > editText.getWidth()
                - editText.getPaddingRight()
                - drawable.getIntrinsicWidth()) {
            editText.setText("");
        }
        return false;
    }
}
